<template>
  <div>
    <Tabs v-model="showTabPanel" type="card" @on-click="tabsClickEvent">
      <TabPane name="aTab" label="设备信息" class="padding5">
        <Row :gutter="10">
          <Col span="8">
            <Form ref="formValidate" :model="virtualObj" :rules="ruleValidate" :label-width="80" class="daaa">
              <FormItem label="设备名称" prop="name">
                <Input v-model="virtualObj.name" placeholder="设备名称"></Input>
              </FormItem>
              <FormItem label="设备编号" prop="sn">
                <Input v-model="virtualObj.sn" placeholder="设备编号"></Input>
              </FormItem>
              <FormItem label="设备图片" prop="pic">
                <Select v-model="virtualObj.pic" style="width:100%;" :transfer="true">
                  <Option v-for="(item,index) in picTypes" :value="item.valueStr" :key="'valueStr'+index">{{ item.name }}</Option>
                </Select>
              </FormItem>
              <FormItem label="所属空间" prop="deviceSpaceText">
                <Cascader change-on-select :render-format="cascaderFormat" trigger="click" :data="deviceSpaceData"
                          v-model="virtualObj.deviceSpace">
                  <Input v-model="virtualObj.deviceSpaceText" readonly placeholder="请选择设备空间"></Input>
                </Cascader>
              </FormItem>
              <FormItem label="排序值" prop="sort">
                <Input v-model="virtualObj.sort" placeholder="排序值"></Input>
              </FormItem>
            </Form>
            <Row class="ddxx">
              属性数据
            </Row>
            <div>
              <table class="tableOne">
                <tr>
                  <th style="width: 120px;">名称</th>
                  <th style="width: 120px;">别名</th>
                  <th style="width: 50px;">单位</th>
<!--                  <th style="width: 50px;">上限</th>-->
<!--                  <th style="width: 50px;">下限</th>-->
                  <th style="width: auto;">操作</th>
                </tr>
              </table>
              <div style="height: 365px;overflow-y: auto;">
                <table class="tableOne">
                  <tr v-for="(item,index) in virtualObj.virtualItems" :key="index" @dblclick="doEditPro(item,index)"
                      style="cursor: pointer;">
                    <td style="width: 120px;text-align: center">
                      {{item.name}}
                    </td>
                    <td style="width: 120px;text-align: center">
                      {{item.alias}}
                    </td>
                    <td style="width: 50px;text-align: center">
                      {{item.unit}}
                    </td>
                  <!--  <td style="width: 50px;text-align: center">
                      {{item.lowLimit}}
                    </td>
                    <td style="width: 50px;text-align: center">
                      {{item.upperLimit}}
                    </td>-->

                    <td style="width: auto;text-align: center">
                      <Button type="error" @click="delItem(index)">删除</Button>
                      <Button type="error" @click="moveUp(index)">上</Button>
                      <Button type="error" @click="moveDown(index)">下</Button>
                    </td>
                  </tr>
                </table>
              </div>
            </div>
            <div class="ddqq">
              <Button type="primary" long @click="doSave" :loading="saveingLoading">保存组合设备</Button>
            </div>
          </Col>
          <Col span="16">
            <div class="dxx">
              <Row>
              <Col span="10">
                <Input v-model="devQryComtent" prefix="ios-search-outline" placeholder="搜索内容" @on-enter="searchDev" style="margin-bottom: 8px"/>
                <Table :loading="devDataLoading" highlight-row border :columns="devCols" :data="devTableList" ref="devTable" size="small" height="382" @on-row-click="devRowClick"></Table>
                <Row style="text-align:right;padding:10px 0;">
                  <Page :total="pageObj.total" size="small" :page-size="pageObj.size" @on-change="devPageChange"></Page>
                </Row>
              </Col>
              <Col span="13" style="margin-left: 40px;">
                <Row :gutter="5" style="margin-bottom: 15px">
                  <Col span="12">
                    <H3>{{selectDevObj.name}}_{{selectDevObj.sn}}</H3>
                  </Col>
                  <Col span="12">
                    <Button type="primary" size="small" style="width: 60px;float: right" @click="doAddToLeft" :disabled="canBeDel">添加</Button>
                  </Col>
                </Row>
                <Table :loading="proDataLoading" border :columns="proCols" :data="proTableList" ref="proTable" size="small" height="382" @on-selection-change="tableCheckbox"></Table>
              </Col>
              </Row>
              <Row>
              <div style="margin-top: 20px">
                <div class="ooaa">
                  <Row :gutter="15">
                    <Col span="4">
                      <Input v-model="virtualItem.name" placeholder="属性名称"/>
                    </Col>
                    <Col span="4">
                      <Input v-model="virtualItem.alias" placeholder="属性别名"/>
                    </Col>

                   <!-- <Col span="3">
                      <Input v-model="virtualItem.refDevId" placeholder="设备ID" disabled/>
                    </Col>
                    <Col span="3">
                      <Input v-model="virtualItem.refCollId" placeholder="属性ID" disabled/>
                    </Col>-->
                    <Col span="3" push style="margin-right: 5px">
                      <!-- <Select v-model="virtualItem.propertyType" :transfer="true" placeholder="属性类别"> -->
                      <Select v-model="virtualItem.propertyType" :transfer="true" placeholder="属性类别">
                        <Option v-for="(item,index) in propertyTypes" :value="item.value" :key="'propertyType'+index">{{ item.name }}
                        </Option>
                      </Select>
                    </Col>
                    <Col span="3">
                      <Select v-model="virtualItem.unit" :transfer="true" placeholder="单位">
                        <Option v-for="(item,index) in units" :value="item.name" :key="'unit'+index">{{ item.name }}
                        </Option>
                      </Select>
                    </Col>
                    <Col span="4">
                      <Input v-model="virtualItem.lowLimit" placeholder="上限"/>
                    </Col>
                    <Col span="4">
                      <Input v-model="virtualItem.upperLimit" placeholder="下限"/>
                    </Col>

                  </Row>
                  <Row :gutter="15" style="padding-top: 15px">
                    <Col span="4" push>
                      日志 <Switch v-model="virtualItem.isLog" :true-value="1" :false-value="0" />
                    </Col>
                    <Col span="4" push>
                      采集 <Switch v-model="virtualItem.isGet" :true-value="1" :false-value="0" />
                    </Col>
                  </Row>
                  <Row :gutter="15" style="margin-top: 10px">
                    <Col span="24">
                      属性计算方式<Input v-model="virtualItem.formula" type="textarea" :autosize="{minRows: 2,maxRows: 2}"
                                   placeholder="属性计算方式..."></Input>
                    </Col>
                  </Row>

                </div>
                <div class="ddqq">
                  <Row :gutter="24">
                    <Col span="8">
                    </Col>
                    <Col span="8">
                      <Button type="primary" long @click="doAdd"
                              :disabled="virtualItem.name === ''">
                        保存编辑
                      </Button>
                    </Col>
                  </Row>
                </div>
              </div>
              </Row>
            </div>
          </Col>
        </Row>
      </TabPane>
      <TabPane name="fourTab" label="参数设定" class="padding5">
        <DevParams ref="devParams"></DevParams>
      </TabPane>
      <TabPane name="cTab" label="控制信息" class="padding5">
        <div class="tabLeft">
          <H3>控制设备数据</H3>
          <div>
            <table class="tableOne">
              <tr>
                <th style="width: 100px;">设备名称</th>
                <th style="width: 90px;">设备ID</th>
                <th style="width: 110px;">控制命令</th>
                <th style="width: 110px;">被控属性</th>
                <th style="width: 50px;">传参</th>
                <th style="width: 110px;">备注说明</th>
                <th style="width: auto;">操作</th>
              </tr>
            </table>
            <div style="height: 420px;overflow-y: auto;">
              <table class="tableOne">
                <tr v-for="(item,index) in ctrlProcessDatas" :key="index" style="cursor: pointer;" @dblclick="doClikdd(item, index)">
                  <td style="width: 100px;text-align: center">
                    {{item.name}}
                  </td>
                  <td style="width: 90px;text-align: center">
                    {{item.devId}}
                  </td>
                  <td style="width: 110px;text-align: center">
                    {{item.command}}
                  </td>
                  <td style="width: 110px;text-align: center">
                    {{item.prop}}
                  </td>
                  <td style="width: 50px;text-align: center">
                    {{item.ifParam? '是' : '否'}}
                  </td>
                  <td style="width: 110px;text-align: center">
                    {{item.remark}}
                  </td>
                  <td style="width: auto;text-align: center">
                    <Button type="error" @click="delItemCtrl(index)">删除</Button>
                    <Button type="error" @click="moveUpCtrl(index)" style="margin-top: 5px;">上移</Button>
                  </td>
                </tr>
              </table>
            </div>
          </div>
        </div>
        <div class="tabRight">
          <Row :gutter="5">
          <div style="width: 60%;float: left;">
            <Input v-model="devQryComtentCtrl" prefix="ios-search-outline" placeholder="搜索内容" @on-enter="searchDevCtrl" style="margin-bottom: 8px"/>
            <Table :loading="devDataLoadingCtrl" highlight-row border :columns="devColsCtrl" :data="devTableListCtrl" ref="devTable" size="small" height="480" @on-row-click="devRowClickCtrl"></Table>
            <Row style="text-align:right;padding:10px 0;">
              <Page :total="pageObjCtrl.total" size="small" :page-size="pageObjCtrl.size" @on-change="devPageChangeCtrl"></Page>
            </Row>
          </div>
          <div style="width: 38%;float: left;margin-left: 1%">
            <Table :loading="proDataLoadingCtrl" border :columns="proCtrlCols" :data="proCtrlTableList" ref="proCtrlTable" size="small" height="520"></Table>
          </div>
          </Row>
          <Row :gutter="5">
            <Col span="4">
              设备名称
              <Input v-model="ctrlDevObj.name" placeholder="设备名称"/>
            </Col>
            <Col span="4">
              设备ID
              <Input v-model="ctrlDevObj.devId" placeholder="设备ID"/>
            </Col>
            <Col span="4">
              控制命令
              <Input v-model="ctrlDevObj.command" placeholder="控制命令"/>
            </Col>
            <Col span="4">
              被控属性
              <Input v-model="ctrlDevObj.prop" placeholder="被控属性"/>
            </Col>
            <Col span="4">
              备注说明
              <Input v-model="ctrlDevObj.remark" placeholder="备注说明"/>
            </Col>
            <Col span="4">
              是否传参
              <br>
              <div style="padding: 5px 0px;">
                <Switch v-model="ctrlDevObj.ifParam" size="large"/>
              </div>
            </Col>
          </Row>
          <Row style="margin-top: 10px;">
            <Col span="24">
              <Button type="primary" style="float: right;width: 150px" @click="moveToLeft">保存</Button>
              <Button type="default" style="float: right;width: 150px;margin-right: 5px;" @click="doYourEmpty">清空</Button>
            </Col>
          </Row>
        </div>
      </TabPane>
      <TabPane name="bTab" label="脚本代码" class="padding5">
        <ScriptPanel ref="refScript" @sonCallSave="saveOrUpd"></ScriptPanel>
      </TabPane>
    </Tabs>
  </div>
</template>

<script>
  import ScriptPanel from '../type/ScriptPanel'
  import DevParams from '../manage/DevParams.vue'
  export default {
    name: 'GroupDevice',
    components: {
      ScriptPanel,
      DevParams
    },
    mounted: function () {
      this.loadSpaceDatas()
      this.loadUnits()
      this.loadPicTypes()
      this.loadPropertyTypes()
    },
    data () {
      return {
        pageObj: {total: 0, size: 20, index: 0},
        pageObjCtrl: {total: 0, size: 20, index: 0},
        devTableList: [],
        devTableListCtrl: [],
        proTableList: [],
        proCtrlTableList: [],
        devDataLoading: false,
        devDataLoadingCtrl: false,
        proDataLoading: false,
        proDataLoadingCtrl: false,
        canBeDel: false,
        devQryComtent: '',
        devQryComtentCtrl: '',
        totalElements: 0,
        proSelectLists: [],
        ctrlProcessDatas: [],
        selectDevObj: {},
        ctrlDevObj: {},
        devCols: [
          {
            title: 'ID',
            key: 'id',
            width: 80,
            align: 'center'
          },
          {
            title: '类型',
            width: 80,
            ellipsis: true,
            tooltip: true,
            align: 'center',
            render: (h, params) => {
              let txt = ''
              if (params.row.type === 0) {
                txt = '真实'
              } else if (params.row.type === 1) {
                txt = '虚拟'
              } else {
                txt = '组合'
              }
              return h('div', [
                h('span', txt)
              ])
            }
          },
          {
            title: '名称',
            key: 'name',
            width: 150,
            ellipsis: true,
            tooltip: true,
            align: 'center'
          },
          {
          title: '编号',
          key: 'sn',
          ellipsis: true,
          tooltip: true,
          align: 'center'
          }
          ],
        devColsCtrl: [
          {
            title: 'ID',
            key: 'id',
            width: 80,
            align: 'center'
          },
          {
            title: '名称',
            key: 'name',
            ellipsis: true,
            tooltip: true,
            align: 'center'
          },
          {
          title: '编号',
          key: 'sn',
          ellipsis: true,
          tooltip: true,
          align: 'center'
          }
          ],
        proCols: [
          {
            type: 'selection',
            width: 60,
            fixed: 'left',
            align: 'center',
            render: (h, params) => {
              let txt = ''
              return h('div', [
                h('span', txt)
              ])
            }
          },
          // {
          //   title: 'ID',
          //   key: 'id',
          //   width: 80,
          //   align: 'center'
          // },
          {
            title: '名称',
            key: 'name',
            ellipsis: true,
            tooltip: true,
            width: 130,
            align: 'center'
          },
          {
            title: '公式',
            ellipsis: true,
            tooltip: true,
            align: 'center',
            render: (h, params) => {
              let txt = this.selectDevObj.sn + '.' + params.row.name
              return h('div', [
                h('span', txt)
              ])
            }
          },
          {
            title: '快捷操作',
            key: 'action',
            fixed: 'right',
            align: 'center',
            width: 150,
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    'margin-right': '15px'
                    // color: '#2db7f5'
                  },
                  on: {
                    click: () => {
                      let txt = this.selectDevObj.sn + '.' + params.row.name
                      if (!this.virtualItem.formula) {
                        this.virtualItem.formula = txt
                        return
                      }
                      this.virtualItem.formula = this.virtualItem.formula.trim().concat(txt)
                    }
                  }
                }, '引用'),
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      let detaText = 'deta(' + `'` + this.selectDevObj.sn + `','` + params.row.name + `')`
                      if (!this.virtualItem.formula) {
                        this.virtualItem.formula = detaText
                        return
                      }
                      this.virtualItem.formula = this.virtualItem.formula.trim().concat(detaText)
                    }
                  }
                }, '计算')
              ])
            }
          }
        ],
        proCtrlCols: [
          {
            title: '属性ID',
            key: 'id',
            width: 80,
            align: 'center'
          },
          {
            title: '属性名',
            key: 'name',
            ellipsis: true,
            tooltip: true,
            align: 'center'
          },
          {
            title: '地址码',
            key: 'valueAddr',
            ellipsis: true,
            tooltip: true,
            align: 'center'
          }
        ],
        updateInit: true,
        deviceSpaceData: [], // 空间选择数据
        total: 0,
        showTabPanel: 'aTab',
        saveingLoading: false,
        units: [],
        picTypes: [],
        tableLoading: false,
        propertyTypes: [],
        pageable: {
          page: 1,
          size: 10,
          type: 0,
          param: ''
        },
        columns1: [
          {
            title: '属性ID',
            width: 80,
            fixed: 'left',
            key: 'proId'
          },
          {
            title: '属性名称',
            key: 'proName',
            fixed: 'left',
            ellipsis: true,
            tooltip: true,
            align: 'center'
          },
          {
            title: '设备ID',
            width: 80,
            fixed: 'left',
            key: 'devId'
          },
          {
            title: '设备名称',
            key: 'devName',
            width: 200,
            ellipsis: true,
            tooltip: true,
            align: 'center'
          },
          {
            title: '设备编号',
            key: 'snName',
            width: 120,
            ellipsis: true,
            tooltip: true,
            align: 'center'
          },
          {
            title: '设备空间',
            key: 'spaceName',
            ellipsis: true,
            tooltip: true,
            align: 'center'
          },
          {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 100,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'info',
                    ghost: true,
                    size: 'small',
                    icon: 'ios-create-outline'
                  },
                  style: {
                    margin: '3px'
                    // color: '#2db7f5'
                  },
                  on: {
                    click: () => {
                      this.doCopy(params.row)
                    }
                  }
                }, '复制')

              ])
            }
          }
        ],
        data1: [],
        devType: '真实设备',
        virtualItem: {
          name: '',
          formula: ''
        },
        editFun: '',
        virtualObj: {
          sn: '',
          name: '',
          deviceSpaceText: '',
          sort: ''
        },
        ruleValidate: {
          name: [
            {required: true, message: '必填项', trigger: 'blur'}
          ],
          sn: [
            {required: true, message: '必填项', trigger: 'blur'}
          ],
          pic: [
            {required: true, message: '必填项', trigger: 'blur'}
          ],
          deviceSpaceText: [
            {required: true, message: '必填项', trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      doClikdd (item, index) {
        this.ctrlDevObj = JSON.parse(JSON.stringify(item))
        this.ctrlDevObj.index = index
      },
      loadPropertyTypes () {
        // 加载属性类别数据
        let pageab = {
          size: 9999,
          page: 0,
          groupType_eq: 1004
        }
        window.myapi.dict_list(pageab).then(resp => {
          if (resp.status === 200 && resp.data.status === 200) {
            this.propertyTypes = resp.data.data.content
          }
        }).finally(() => {
        })
      },
      tabsClickEvent: function (name) {
        if (name === 'cTab' && this.devTableListCtrl.length === 0) {
          this.loadDevDatasCtrl()
        }
      },
      doYourEmpty: function () {
        this.ctrlDevObj = {}
      },
      moveToLeft: function () {
        // this.ctrlProcessDatas.push(this.ctrlDevObj)
        if (!this.ctrlDevObj.name) {
          this.$Message.info('属性名称不能为空')
          return
        }
        let findOne = this.ctrlProcessDatas[this.ctrlDevObj.index]
        if (findOne) {
          this.ctrlProcessDatas.splice(this.ctrlDevObj.index, 1, this.ctrlDevObj)
        } else {
          this.ctrlProcessDatas.push(this.ctrlDevObj)
        }

        this.ctrlDevObj = {}
        this.updateSortValueCtrl()
      },
      devPageChange: function (index) {
        this.pageObj.index = index - 1
        this.loadDevDatas()
      },
      devPageChangeCtrl: function (index) {
        this.pageObjCtrl.index = index - 1
        this.loadDevDatasCtrl()
      },
      doAddToLeft: function () {
        // 检测选项
        if (this.proSelectLists.length === 0) {
          this.$Message.info('没有选择数据....')
          return
        }
        // 检测所选设备是否含有 设备编号sn
        if (!this.selectDevObj.sn) {
          this.$Message.info('当前所选设备没有配置【设备编号】，无法复制属性')
          return
        }
        let handleSelections = this.proSelectLists.map(item => {
          let doHandleObj = {
            isGet: 1,
            isLog: 1,
            unit: item.unit,
            type: item.type,
            alias: item.name,
            propertyType: item.propertyType,
            name: item.name,
            formula: this.selectDevObj.sn + '.' + item.name
          }
          return doHandleObj
        })
        this.virtualObj.virtualItems.push(...handleSelections)
        this.proSelectLists = []
        this.$refs.proTable.selectAll(false)
      },
      // tableCheckbox变化
      tableCheckbox: function (selection) {
        this.proSelectLists = selection
        if (this.proSelectLists.length > 0) {
          this.canBeDel = false
        } else {
          this.canBeDel = true
        }
      },
      devRowClick: function (row, index) {
        let devType = row.type
        this.proTableList = []
        this.proDataLoading = true
        this.selectDevObj = JSON.parse(JSON.stringify(row))
        if (devType === 1 || devType === 2) {
          this.proTableList = row.virtualItems
          this.proDataLoading = false
          return
        }
        this.proTableList = row.iotDevType.iotCollItems
        this.proDataLoading = false
      },
      devRowClickCtrl: function (row, index) {
        this.proDataLoadingCtrl = true
        this.proCtrlTableList = []
        if (!this.ctrlDevObj.devId) {
          this.ctrlDevObj = {
            'name': row.name,
            'devId': row.id
          }
        }
        if (row.type === 0) {
          this.proCtrlTableList = row.iotDevType.iotCollItems
        }
        this.proDataLoadingCtrl = false
      },
      loadDevDatas () {
        this.proTableList = []
        this.proSelectLists = []
        this.$refs.proTable.selectAll(false)
        let getData = {
          'size': this.pageObj.size,
          'page': this.pageObj.index,
          'keyword': this.devQryComtent
        }
        this.devDataLoading = true
        window.myapi.do_gett('/iot/dev/listt', getData).then((res) => {
          this.tableList = []
          if (res.data.status === 200) {
            this.devTableList = res.data.data.content
            this.totalElements = res.data.data.totalElements
            this.pageObj.size = res.data.data.size
            this.pageObj.total = res.data.data.totalElements
          } else {
            let msg = res.data.msg ? res.data.msg : '请求数据失败!'
            this.$Message.error({ content: msg, duration: 5, closable: true })
          }
        }).catch(function (e) {
          if (e && e.response && e.response.data) {
            let msg = e.response.data.message ? e.response.data.message : '请求数据失败!'
            this.$Message.error({ content: msg, duration: 5, closable: true })
            this.tableList = []
          }
        }).finally(() => {
          this.devDataLoading = false
        })
      },
      loadDevDatasCtrl () {
        let getData = {
          'size': this.pageObjCtrl.size,
          'page': this.pageObjCtrl.index,
          'keyword': this.devQryComtentCtrl
        }
        this.devDataLoadingCtrl = true
        window.myapi.do_gett('/iot/dev/listt', getData).then((res) => {
          this.tableList = []
          if (res.data.status === 200) {
            this.devTableListCtrl = res.data.data.content
            this.totalElements = res.data.data.totalElements
            this.pageObjCtrl.size = res.data.data.size
            this.pageObjCtrl.total = res.data.data.totalElements
          } else {
            let msg = res.data.msg ? res.data.msg : '请求数据失败!'
            this.$Message.error({ content: msg, duration: 5, closable: true })
          }
        }).catch(function (e) {
          if (e && e.response && e.response.data) {
            let msg = e.response.data.message ? e.response.data.message : '请求数据失败!'
            this.$Message.error({ content: msg, duration: 5, closable: true })
            this.tableList = []
          }
        }).finally(() => {
          this.devDataLoadingCtrl = false
        })
      },
      loadDatas () {
        this.data1 = []
        this.tableLoading = true
        // 加载数据
        window.myapi.do_post('iot/dev/virs', this.pageable).then(resp => {
          if (resp.status === 200 && resp.data.status === 200) {
            let result = resp.data.data
            this.total = result.total
            if (result.list.length > 0) {
              this.data1 = result.list
            }
          }
        }).finally(() => {
          this.tableLoading = false
        })
      },
      searchDev () {
        // 搜索设备
        this.pageObj.index = 0
        this.loadDevDatas()
      },
      searchDevCtrl () {
        // 搜索设备
        this.pageObjCtrl.index = 0
        this.loadDevDatasCtrl()
      },
      loadSpaceDatas () {
        // 加载数据
        window.myapi.do_post('iot/space/cas', this.pageable).then(resp => {
          if (resp.status === 200 && resp.data.status === 200) {
            this.deviceSpaceData = resp.data.data
          }
        }).finally(() => {
        })
      },
      loadUnits () {
        // 加载单位数据
        let pageab = {
          size: 9999,
          page: 0,
          groupType_eq: 1005
        }
        window.myapi.dict_list(pageab).then(resp => {
          if (resp.status === 200 && resp.data.status === 200) {
            this.units = resp.data.data.content
          }
        }).finally(() => {
        })
      },
      loadPicTypes () {
        // 加载设备图片类型数据
        let pageab = {
          size: 9999,
          page: 0,
          groupType_eq: 1008
        }
        window.myapi.dict_list(pageab).then(resp => {
          if (resp.status === 200 && resp.data.status === 200) {
            this.picTypes = resp.data.data.content
          }
        }).finally(() => {
        })
      },
      // 编辑级联选择器
      cascaderFormat: function (labels, selectedData) {
        let self = this
        let index = labels.length - 1
        self.$nextTick(() => {
          if (selectedData.length > 0) {
          // let index = labels.length - 1
          // this.virtualObj.deviceSpaceText = selectedData[index].label
          self.virtualObj = { ...self.virtualObj, ...{deviceSpaceText: ''} }
          if (self.updateInit) {
            self.updateInit = false
            self.virtualObj.deviceSpaceText = labels[0]
          } else {
            self.virtualObj.deviceSpaceText = labels.join('>')
          }
          let spaceObj = {
            id: selectedData[index].value
          }
          self.virtualObj.iotSpace = spaceObj
         }
        //  return labels[index]
        return self.virtualObj.deviceSpaceText
        })
      },
      setAllDefault () {
        // 恢复默认设置
        this.virtualObj = {
          type: 1,
          deviceSpaceText: '',
          virtualItems: []
        }
        this.pageable = {
          page: 1,
          size: 10,
          type: 0,
          param: ''
        }
        this.ctrlDevObj = {}
        this.ctrlProcessDatas = []
        this.makeEmpty()
        this.devType = '真实设备'
        // 清空 代码的填写
        this.$refs.refScript.makeDefault()
        this.$refs.devParams.makeDefault()
      },
      pageChange: function (index) {
        this.pageable.page = index
        this.loadDatas()
      },
      radioChange: function (txt) {
        if (txt === '真实设备') {
          this.pageable.type = 0
        } else {
          this.pageable.type = 1
        }
        this.pageable.page = 1
        this.loadDatas()
      },
      doQuery: function () {
        this.pageable.page = 1
        this.loadDatas()
      },
      acceptEditData (datas) {
        this.virtualObj = JSON.parse(JSON.stringify(datas))
        // this.virtualObj.deviceSpaceText = this.virtualObj.iotSpace.name
        this.virtualObj.deviceSpaceText = this.virtualObj.temporaryVariable
        this.ctrlProcessDatas = this.virtualObj.ctrlProcesses
        this.$refs.refScript.updateFormdata(JSON.parse(JSON.stringify(datas)))
        this.$refs.devParams.devParamsList = this.virtualObj.devParams
        // 加载选项数据
        this.loadDevDatas()
      },
      doSave: function () {
        this.$refs['formValidate'].validate((valid) => {
          if (valid) {
            this.virtualObj.type = 2
            this.saveOrUpd()
          }
        })
      },
      doEditPro: function (obj, index) {
        this.virtualItem = JSON.parse(JSON.stringify(obj))
        this.virtualItem.flag = index
      },
      saveOrUpd: function () {
        this.saveingLoading = true
        let url = ''
        let method = ''
        if (this.virtualObj.id) {
          url = '/iot/dev/upd'
          method = 'PUT'
        } else {
          url = '/iot/dev/save'
          method = 'POST'
        }
        this.updateSortValue()
        // 获取 脚本信息
        this.virtualObj.scriptSwitch = this.$refs.refScript.scriptObj.switch
        this.virtualObj.ctrlProcesses = this.ctrlProcessDatas
        this.virtualObj.devParams = this.$refs.devParams.devParamsList
        this.virtualObj.script = this.$refs.refScript.scriptObj.codes === '' ? '' : this.$refs.refScript.scriptObj.codes
        window.myapi.put_post(url, this.virtualObj, method).then((res) => {
          if (res.data.status === 200) {
            this.$Message.success('保存成功!')
            this.setAllDefault()
            this.callFatherRefresh()
            this.loadDatas()
          } else {
            let msg = res.data.msg ? res.data.msg : '保存失败！'
            this.$Message.error(msg)
          }
        }).catch(e => {
          let msg = e.response.data.message ? e.response.data.message : '保存失败!'
          this.$Message.error({duration: 0, closable: true, content: msg})
        }).finally(() => {
          this.saveingLoading = false
        })
      },
      callFatherRefresh () {
        this.$emit('tell-refresh')
      },
      delItem: function (index) {
        this.virtualObj.virtualItems.splice(index, 1)
        this.makeEmpty()
      },
      delItemCtrl: function (index) {
        this.ctrlProcessDatas.splice(index, 1)
        this.updateSortValueCtrl()
        this.makeEmpty()
      },
      moveUp: function (index) {
        // 上移
        if (index === 0) {
          return
        }
        this.virtualObj.virtualItems[index] = this.virtualObj.virtualItems.splice(index - 1, 1, this.virtualObj.virtualItems[index])[0]
        this.updateSortValue()
      },
      moveDown: function (index) {
        // 下移
        if (index === this.virtualObj.virtualItems.length - 1) {
          return
        }
        this.virtualObj.virtualItems[index] = this.virtualObj.virtualItems.splice(index + 1, 1, this.virtualObj.virtualItems[index])[0]
        this.updateSortValue()
      },
      moveUpCtrl: function (index) {
        // 上移
        if (index === 0) {
          return
        }
        this.ctrlProcessDatas[index] = this.ctrlProcessDatas.splice(index - 1, 1, this.ctrlProcessDatas[index])[0]
        this.updateSortValueCtrl()
      },
      updateSortValue () {
        this.virtualObj.virtualItems.map((item, index) => {
          item.sort = index + 1
          return item
        })
      },
      updateSortValueCtrl () {
        this.ctrlProcessDatas.map((item, index) => {
          item.sort = index + 1
          return item
        })
      },
      doCopy: function (row) {
        this.virtualItem = {
          refDevId: row.devId,
          refCollId: row.proId,
          name: row.proName
        }
      },
      makeEmpty: function () {
        // 置空
        this.virtualItem = {
          name: '',
          formula: '',
          isGet: 0,
          isLog: 0
        }
        this.ctrlDevObj = {}
        this.devTableListCtrl = []
        this.proCtrlTableList = []
        this.devQryComtentCtrl = ''
      },
      doAdd: function () {
        if (!this.virtualItem.name) {
          this.$Message.info('属性名称不能为空')
          return
        }
        // let reg = /^[a-zA-Z | _]([\u4e00-\u9fa5\w]{1,50})$/
        // if (!reg.exec(this.virtualItem.name)) {
        //   this.$Message.info('必须以字母或下划线开头，编号可包含英文、数字、下划线')
        //   return false
        // }
        let findOne = this.virtualObj.virtualItems[this.virtualItem.flag]
        if (findOne) {
          this.virtualObj.virtualItems.splice(this.virtualItem.flag, 1, this.virtualItem)
        } else {
          this.virtualObj.virtualItems.push(this.virtualItem)
        }
        this.makeEmpty()
      }
    }
  }
</script>

<style scoped>
  .dxx{
    padding: 0px 20px;
  }
  .ooa{
    margin-top: 10px;
  }
  .ooaa{
    margin-top: 15px;
  }
  .pagg{
    margin-top: 5px;
    text-align: right;
  }
  .ddxx{
    padding-left: 20px;
    font-size: 12px;
    margin-bottom: 5px;
    margin-top: 25px;
  }
  .ddqq{
    margin-top: 16px;
    text-align: center;
  }

  .tableOne {
    width: 100%;
    border-spacing: 0px;
    table-layout: fixed;
  }
  .tabLeft{
    width: 40%;
    padding: 10px;
    float: left;
  }
  .tabRight{
    width: 60%;
    padding: 10px;
    float: left;
  }

  table th,
  td {
    border: 1px solid #e9eaec;
    margin: 0;
    padding: 3px;
  }

  table tr {
    margin: 0;
    height: 32px;
  }

  .columnStyle {
    text-align: center;
  }

  .padding5 {
    padding: 5px;
  }
</style>

<style>
  .daaa .ivu-form-item{
    margin-bottom: 20px;
  }
</style>
